<script setup lang="ts">
import {compile} from "path-to-regexp";
import {onMounted, ref, Ref, watch} from "vue";
import {RouteLocationMatched, RouteLocationRaw, useRoute} from "vue-router";
import router from "../../../../router";

const levelList: Ref<Array<any>> = ref([]);

const route = useRoute();

watch(route, (_) => {
  getBreadcrumb();
})

onMounted(() => {
  getBreadcrumb();
})

const getBreadcrumb = () => {
  let matched = route.matched.filter((item: RouteLocationMatched) => item.meta && item.meta.title);
  const first = matched[0];

  if (!isDashboard(first)) {
    // TODO
  }

  levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false);
}

const isDashboard = (route: RouteLocationMatched): boolean => {
  const name = route && route.name;
  if (!name) {
    return false;
  }

  return name.toString().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase();
}

const pathCompile = (path: string) => {
  const {params} = route;
  let toPath = compile(path);
  return toPath(params);
}

const handleLink = (item: RouteLocationMatched) => {
  const {redirect, path} = item;
  if (redirect) {
    router.push(<RouteLocationRaw>redirect);
    return;
  }
  router.push(pathCompile(path));
}
</script>

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect' || index === levelList.length - 1" class="no-redirect-icon">
          {{item.meta.title}}
        </span>
        <a v-else @click.prevent="handleLink(item)">{{item.meta.title}}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<style scoped lang="scss">
.app-breadcrumb {
  display: flex;
  flex-direction: row;
  justify-content: start;
}
</style>